<?php

namespace Xtsb\Cims\Query;

use Xtsb\Cims\Route\Route;
use think\facade\Db;

class SearchFields
{
  /**
   * @param $url null 索引页路由
   * @param $param null 参数
   * @return void|array
   */
  public static function list($url = null, $param = null)
  {
    $url = $url ?? get_table_name();
    $where['cuid'] = CUID;
    $where['uuid'] = UUID;
    $where['name'] = $url;
    $where['type'] = 2;//2-search配置
    $setupInfo = Db::name('user_site_setup')->field('content')->json(['content'])->where($where)->find();
//    unset($param['url']);

    //获取原始数据
    $searchName = $url;
    if ($url == 'cca') {
      $searchName = 'project_contract';
    } elseif ($url == 'cor') {
      $searchName = 'project';
    } elseif ($url == 'project_ledger') {
      $searchName = 'project_item';
    }

    $serverName = 'app\\Common\\Query\\Fields\\' . Route::getController($searchName);//驼峰法转化
    $list = $serverName::list($param);
    //读取原数据配置信息
    $searchConfig = [];
    foreach ($list as $item) {
      if(!is_array($item)){
        continue;
      }
      $searchConfig[$item['name']] = $item;
    }

    $result = [];
    if ($setupInfo) {
      //存在个人自定义的配置 则读取自定义的配置
      foreach ($setupInfo['content'] as $item) {
        if (isset($searchConfig[$item])) {
          $result[] = $searchConfig[$item];
        }
      }
      return $result;
    } else {
      //读取所有配置
      return $list;
    }
  }

  /**
   * 获取默认搜索条件
   * @param $url
   * @param $param
   * @return array
   */
  public static function defaultFields($prefix = null, $url = null, $param = null)
  {
    if (empty($prefix)) {
      $dbName = $url ?? get_table_name();
      $prefix = config('app.database.prefix') . $dbName;
    }
    $list = self::list($url, $param);

    $where = [];
    foreach ($list as $item) {

      if (isset($item['default'])) {
        switch ($item['type']) {
          case 'input':
            $where[] = [$prefix . $item['name'], 'LIKE', '%' . $item['default'] . '%'];
            break;
          case 'daterange':
            $where[] = [$prefix . $item['name'], 'BETWEEN', $item['default']];
            break;
          default :
            $where[] = [$prefix . $item['name'], '=', $item['default']];
            break;
        }

      }
    }

    return $where;
  }
}